package com.hibase.core.page.utils;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class XStreamUtils {

    private XStreamUtils() {
    }


    private static class SingletonXstream {

        private static XStream xStream = null;
        static {

            if (xStream == null) {
                xStream = new XStream(new DomDriver());
                // 去掉class属性
                xStream.aliasSystemAttribute(null, "class");

//                //自动探测注解
//                xStream.autodetectAnnotations(true);
//                //忽略未知元素
//                xStream.ignoreUnknownElements();
//
//                //避免出现以下警告:Security framework of XStream not initialized, XStream is probably vulnerable
//                XStream.setupDefaultSecurity(xStream);
            }
        }
    }


    public static XStream getInstance() {

        XStream xStream = new XStream(new DomDriver());
        // 去掉class属性
        xStream.aliasSystemAttribute(null, "class");
        return xStream;
//        return SingletonXstream.xStream;
    }

    /**
     * 对象直接转换为XML字符串格式
     *
     * @param t
     * @param <T>
     * @return
     */
    public static <T> String toXml(T t) {
        XStream xstream = XStreamUtils.getInstance();
        xstream.processAnnotations(t.getClass());
        return xstream.toXML(t);
    }

    /**
     * XML直接转化为对象
     *
     * @param xml
     * @param clazz
     * @param <T>
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T toBean(String xml, Class<T> clazz) {
        XStream xstream = XStreamUtils.getInstance();
        xstream.processAnnotations(clazz);
        T obj = (T) xstream.fromXML(xml);
        return obj;
    }
}
